package com.haier.npt.mybatis.plugins.spring.config;

import java.util.Set;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ClassUtils;

import com.baomidou.mybatisplus.annotations.TableName;

public class Scanner extends ClassPathBeanDefinitionScanner {
	
		private BeanDefinitionRegistry  registry ; 
	
		//Spring4.3以后可以实现构造函数注入，Spring会自动从容器中取到参数对应的对象进行注入
		public Scanner(BeanDefinitionRegistry registry) {
			super(registry);
			this.registry = registry; 
		}

		@Override
		public void registerDefaultFilters() {
			//将Mybatis plus 中的 TableName 注解加入spring 的管理，
			this.addIncludeFilter(new AnnotationTypeFilter(TableName.class));
		}
		
		@Override
		public Set<BeanDefinitionHolder> doScan(String... basePackages) {
			Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
			for (BeanDefinitionHolder holder : beanDefinitions) {
				GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
//				Class<?> classzz = definition.getBeanClass(); 
				String beanName = ClassUtils.getShortNameAsProperty(definition.getClass()); 
				registry.registerBeanDefinition(beanName, definition);
				
			}
			return beanDefinitions;
		}
		
		@Override
		public boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
			return super.isCandidateComponent(beanDefinition) && beanDefinition.getMetadata()
					.hasAnnotation(TableName.class.getName());
		}
		
	}

